package codeRandomThoughts.Test111二叉树的最小深度;

import codeRandomThoughts.utils.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

//层序遍历方法
public class Solution4 {
    public int minDepth(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        if (root != null) {
            queue.offer(root);
        }

        int depth = 0;
        while (!queue.isEmpty()) {
            //每层元素数量
            int size = queue.size();
            depth++;
            while (size > 0) {
                TreeNode node = queue.poll();
                //遍历到叶子结点直接返回
                if (node.left == null && node.right == null) {
                    return depth;
                }
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                size--;
            }
        }

        return depth;
    }
}
